#!/usr/bin/env bash
# automountntfs.sh
# Mounts all the drives inside a NTFS formatted device automatically.


echo -e "\nWARNING! This script is experimental, so it may not work as expected. Only tested on FreeBSD 13.\n"

if [ -z "$(which ntfs-3g)" ]; then
	echo 'ntfs-3g is not found. Please install ntfs-3g and continue.'; exit 6725
fi
if [[ "$1" = /dev/* ]]; then
	DEVICE="$1"
	DEVICE_ID=$(echo "$1" | sed -r 's|\/dev\/(.*)|\1|')
else
	DEVICE_ID="$1"
	DEVICE="/dev/${DEVICE_ID}"
fi
if [ -z "$1" ]; then
	echo -e "Empty device is not allowed.\nPlease provide a device to mount drives from, such as:\n  $0 /dev/ada0"; exit 9482
fi
if [ ! -e "${DEVICE}" ]; then
	echo "Device ${DEVICE} doesn't exist"; exit 2529
fi

ls ${DEVICE}s* | while read line
do
	echo "Trying to mount $line..."
	part_label=$(ntfslabel "${line}")
	if [ -z "${part_label}" ]; then # no label
		mount_dir=$(echo "${line}" | sed -r 's|\/dev\/(.*)|\1|')
	else # has label
		mount_dir="${part_label}"
	fi
	# Check to see if already mounted. This is to avoid multiple duplicate devices showing up.
	# This happens when this script is run multiple times.
	if [[ ! -z "$(mount | grep "/media/${DEVICE_ID}/${mount_dir} ")" ]]; then
		echo "Device ${line} already mounted. Assuming duplicate entry and ignoring..."
	else
		# Mounting it on /media, instead of /mnt shows it on file manager sidebar.
		sudo mkdir -p "/media/${DEVICE_ID}/${mount_dir}"
		sudo ntfs-3g "${line}" "/media/${DEVICE_ID}/${mount_dir}"
	fi
done
